import {
  exportAiHistoryList,
  getAiHistoryStudyList,
  getAllAiStudyList,
  getCycleByPlan,
  HistoryItemType,
  HistoryListSearchParams,
} from '@/api/AiStatisticApi';
import { Button, Form } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmAddPageLayout, YmTable, type YmAddPageLayoutProps } from 'ym-design';

type SearchValue = Partial<HistoryListSearchParams>;
type TableRecord = HistoryItemType;
const { PaneItem } = YmAddPageLayout;
export default function AiHistoryStudyPlanPage() {
  const navigator = useNavigate();
  const [searchValue, setSearchValue] = useState<HistoryListSearchParams>();
  const [form] = Form.useForm();
  // todo 强制更新方法
  const [force, _forceUpdate] = useState<number>();
  const forceUpdate = () => {
    _forceUpdate(Math.random());
  };

  //计划名称筛选项
  const [selectPlanId, setSelectPlanId] = useState<string>(); //计划id
  const [ownCoursePlanList, setOwnCoursePlanList] = useState<{ label: string; value: string }[]>([]); //自建计划
  const [selectCycleId, setSelectCycleId] = useState<string>(); //周期id
  const [cycleList, setCycleList] = useState<{ label: string; value: string }[]>([]); //周期筛选项

  const getPlanOptions = async () => {
    const data = await getAllAiStudyList(1, 999999);
    const aiPlanList = data.list;
    const planOption: { label: string; value: string }[] = [];
    aiPlanList.map((v) => {
      planOption.push({ label: v.title, value: v.aiPlanId });
    });
    setOwnCoursePlanList([...planOption]);
    planOption.length ? setSelectPlanId(planOption[0].value) : null;
  };

  //初始化获取计划下拉列表
  useEffect(() => {
    getPlanOptions();
  }, []);

  //周期循环筛选项
  const getCycleByPlanTime = async () => {
    const cList = selectPlanId ? await getCycleByPlan(selectPlanId) : [];
    const cycleOption: { label: string; value: string }[] = [];
    cList.map((v) => {
      cycleOption.push({ label: v.startTime + '~' + v.endTime, value: v.aiCycleId });
    });
    setCycleList([...cycleOption]);
    cycleOption.length ? setSelectCycleId(cycleOption[0].value) : setSelectCycleId('');
  };

  //获取周期时间下拉列表
  useEffect(() => {
    getCycleByPlanTime();
  }, [selectPlanId]);

  //设置表格计划和周期查询值
  useEffect(() => {
    if (selectCycleId) {
      console.log('selectCycleId', selectCycleId);
      form.setFieldValue('aiPlanId', selectPlanId);
      form.setFieldValue('aiCycleId', selectCycleId);
      forceUpdate();
    }
  }, [selectCycleId]);

  //表格数据
  const columns: YmColumnsType<TableRecord> = useMemo(
    () => [
      {
        title: '计划名称',
        dataIndex: 'title',
        key: 'title',
        width: 200,
        ellipsis: true,
      },
      {
        title: '学习时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 250,
        ellipsis: true,
        render: (text, record) => <span>{record.startTime + '-' + record.endTime}</span>,
      },
      {
        title: '姓名',
        dataIndex: 'personName',
        key: 'personName',
        width: 100,
        ellipsis: true,
      },
      {
        title: '电话号码',
        dataIndex: 'phone',
        key: 'phone',
        width: 120,
        ellipsis: true,
      },
      {
        title: '企业名称',
        dataIndex: 'entName',
        key: 'entName',
        width: 200,
        ellipsis: true,
      },
      {
        title: '完成时间',
        dataIndex: 'finishTime',
        key: 'finishTime',
        width: 220,
        ellipsis: true,
      },
      {
        title: '学习状态',
        dataIndex: 'finishState',
        key: 'finishState',
        width: 80,
        ellipsis: true,
        render: (text, record) =>
          record.finishState == '2' ? (
            <span style={{ color: '#FF4A4A' }}>未学习</span>
          ) : (
            <span style={{ color: '#3BD59A' }}>已学习</span>
          ),
      },
    ],
    [],
  );

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          navigator(-1);
        },
      },
      destroyInactiveTabPane: false,
    }),
    [],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={'历史学习情况'} className="pane_tab1">
        <div style={{ background: '#fff', width: '100%', height: 'calc(100vh - 118px)', minHeight: '730px' }}>
          <YmTable<TableRecord, SearchValue>
            rowKey="No"
            columns={columns}
            toolBar={{
              prefixNode: (
                <>
                  <Button
                    type="primary"
                    disabled={!searchValue || !searchValue?.aiPlanId}
                    onClick={() => {
                      exportAiHistoryList({ ...searchValue });
                    }}
                  >
                    导出查询记录
                  </Button>
                </>
              ),
            }}
            searchForm={{
              hiddenReset: true,
              span: 6,
              formItems: [
                {
                  name: 'aiPlanId',
                  label: '计划名称',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      options: ownCoursePlanList,
                      showSearch: false,
                      maxTagCount: 1,
                      onChange: (value) => {
                        setSelectPlanId(value);
                        form.setFieldValue('aiPlanId', value);
                      },
                    },
                  },
                },
                {
                  name: 'aiCycleId',
                  label: '学习时间',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      options: cycleList,
                      showSearch: false,
                      maxTagCount: 1,
                      popupMatchSelectWidth: true,
                    },
                  },
                },
                {
                  name: 'finishState',
                  label: '学习状态',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      defaultValue: '',
                      options: [
                        { label: '全部', value: '' },
                        { label: '已学习', value: 1 },
                        { label: '未学习', value: 2 },
                      ],
                      showSearch: false,
                      maxTagCount: 1,
                    },
                  },
                },
              ],
              // initialValues,
              form,
            }}
            request={async ({ page }, value = {}) => {
              setSearchValue({ ...value });
              if (!value.aiCycleId || !value.aiPlanId) {
                return { list: [], total: 0 };
              }
              const result = await getAiHistoryStudyList({ ...value }, page?.pageIndex, page?.pageSize);
              return result;
            }}
            requestOptions={{
              ready: selectCycleId ? true : false,
              reFreshDep: [force],
            }}
          />
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}
